package com.woniu.atms.controller.pre;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.atms.entity.G5Passenger;
import com.woniu.atms.service.G5PassengerService;
import com.woniu.atms.util.Audience;
import com.woniu.atms.util.Code;
import com.woniu.atms.util.JwtUtil;
import com.woniu.atms.util.ResponseResult;
import com.woniu.atms.vo.JwtVO;
import com.woniu.atms.vo.pre.passenger.PassengerAddTokenVO;
import com.woniu.atms.vo.pre.passenger.PassengerPageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 张杰
 * @title: PrePassengerController 乘车人管理
 * @projectName g5_atms
 * @description: TODO
 * @date 2022/1/17 15:05
 */
@Api(tags = "乘车人管理（前台）")
@RestController
@RequestMapping("/api/pre/v1/passenger")
public class PrePassengerController {
    @Autowired
    private G5PassengerService g5PassengerService;
    @Autowired
    private Audience audience;

    /**
     * 所有乘车人信息
     *
     * @return 返回统一响应
     */
    @ApiOperation(value = "所有乘车人信息", notes = "所有乘车人信息，参数为用户id(展示出来的都是未被逻辑删除的)")
    @GetMapping("/all")
    public ResponseResult all() {
        return new ResponseResult(g5PassengerService.list());
    }

    /**
     * 乘车人信息(根据userid)
     * @param jwtVO
     * @return
     */
    @ApiOperation(value = "乘车人信息(根据userid,is_exit=y)", notes = "乘车人信息，参数为用户id(展示出来的都是未被逻辑删除的)")
    @RequestMapping("/info")
    public ResponseResult info(@RequestBody @Valid JwtVO jwtVO) {
        int id = JwtUtil.parseJwtForId(jwtVO.getToken(), audience);
        return new ResponseResult<>(g5PassengerService.findByUserIdY(id));
    }

    /**
     * 乘车人信息
     *
     * @param g5Passenger 乘车人信息
     * @return 返回统一响应
     */
    @ApiOperation(value = "乘车人信息", notes = "乘车人信息，参数为乘车人信息")
    @RequestMapping("/msg")
    public ResponseResult msg(@RequestBody G5Passenger g5Passenger) {
        return new ResponseResult<>(g5PassengerService.queryById(g5Passenger.getId()));
    }

    /**
     * 乘车人信息
     * (分页)
     *
     * @param passengerPageVO 乘车人分页查询视图（筛选条件,起始页,每页条数）
     * @return 返回统一响应
     */
    @ApiOperation(value = "分页查询乘车人信息", notes = "分页查询乘车人信息（可设多条件，姓名、身份证号、手机号、邮箱可以模糊条件），参数为乘车人分页查询视图")
    @RequestMapping("/page")
    public ResponseResult page(@RequestBody @Validated PassengerPageVO passengerPageVO) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", passengerPageVO.getG5Passenger().getId());
        map.put("name", passengerPageVO.getG5Passenger().getName());
        map.put("gender", passengerPageVO.getG5Passenger().getGender());
        map.put("idCard", passengerPageVO.getG5Passenger().getIdCard());
        map.put("telephone", passengerPageVO.getG5Passenger().getTelephone());
        map.put("email", passengerPageVO.getG5Passenger().getEmail());
        map.put("userId", passengerPageVO.getG5Passenger().getUserId());
        map.put("isOk", passengerPageVO.getG5Passenger().getIsOk());
        map.put("isExit", passengerPageVO.getG5Passenger().getIsExit());
        return new ResponseResult<>(this.g5PassengerService.findByPage(map, passengerPageVO.getPageNum(), passengerPageVO.getPageSize()));
    }

    /**
     * 添加乘车人
     *
     * @param g5Passenger 乘车人信息
     * @return 返回统一响应
     */
    @ApiOperation(value = "添加乘车人", notes = "添加乘车人，参数为乘车人信息（判断新添加的乘车人是否是以前逻辑删除状态，是则修改状态，不是则新增）")
    @PostMapping("/add")
    public ResponseResult<Void> add(@RequestBody @Validated G5Passenger g5Passenger) {
        if ("".equals(g5Passenger.getName())) {
            return new ResponseResult(Code.FAIL, "请输入乘车人姓名！");
        }
        if ("".equals(g5Passenger.getGender())) {
            return new ResponseResult(Code.FAIL, "请输入乘车人性别！");
        }
        if ("".equals(g5Passenger.getIdCard())) {
            return new ResponseResult(Code.FAIL, "请输入乘车人身份证号！");
        }
        if ("".equals(g5Passenger.getTelephone())) {
            return new ResponseResult(Code.FAIL, "请输入乘车人手机号！");
        }
        if ("".equals(g5Passenger.getEmail())) {
            return new ResponseResult(Code.FAIL, "请输入乘车人邮箱！");
        }
        //通过身份证号判断是否为同一乘车人
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id_card", g5Passenger.getIdCard());
        long p = g5PassengerService.count(queryWrapper);
        G5Passenger p1 = g5PassengerService.getOne(queryWrapper);
        //新增乘车人
        if (p == 0) {
            g5PassengerService.insert(g5Passenger);
            return ResponseResult.SUCCESS;
            //要添加的乘车人为被逻辑删除状态，所以修改其状态
        } else if (p == 1) {
            if ("n".equals(p1.getIsExit())) {
                p1.setName(g5Passenger.getName());
                p1.setGender(g5Passenger.getGender());
                p1.setIdCard(g5Passenger.getIdCard());
                p1.setTelephone(g5Passenger.getTelephone());
                p1.setEmail(g5Passenger.getEmail());
                p1.setIsExit("y");
                g5PassengerService.update(p1);
                return ResponseResult.SUCCESS;
            }
        }
        return new ResponseResult(Code.FAIL, "该乘车人已存在！");
    }

    /**
     * 添加乘车人(token)
     *
     * @param vo 乘车人信息vo
     * @return 返回统一响应
     */
    @ApiOperation(value = "添加乘车人", notes = "添加乘车人，参数为乘车人信息（判断新添加的乘车人是否是以前逻辑删除状态，是则修改状态，不是则新增）")
    @PostMapping("/add_token")
    public ResponseResult<Void> addToken(@RequestBody @Valid PassengerAddTokenVO vo) {
        int id = JwtUtil.parseJwtForId(vo.getToken(), audience);
        if (id <= 0) {
            return new ResponseResult(Code.SUCCESS, "非法token", id);
        }

        G5Passenger g5Passenger = new G5Passenger();
        BeanUtils.copyProperties(vo, g5Passenger);
        g5Passenger.setUserId(id);
        if ("".equals(g5Passenger.getName())) {
            return new ResponseResult(Code.FAIL, "请输入乘车人姓名！");
        }
        if ("".equals(g5Passenger.getGender())) {
            return new ResponseResult(Code.FAIL, "请输入乘车人性别！");
        }
        if ("".equals(g5Passenger.getIdCard())) {
            return new ResponseResult(Code.FAIL, "请输入乘车人身份证号！");
        }
        if ("".equals(g5Passenger.getTelephone())) {
            return new ResponseResult(Code.FAIL, "请输入乘车人手机号！");
        }
        if ("".equals(g5Passenger.getEmail())) {
            return new ResponseResult(Code.FAIL, "请输入乘车人邮箱！");
        }
        //通过身份证号判断是否为同一乘车人
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id_card", g5Passenger.getIdCard());
        long p = g5PassengerService.count(queryWrapper);
        G5Passenger p1 = g5PassengerService.getOne(queryWrapper);
        //新增乘车人
        if (p == 0) {
            g5PassengerService.insert(g5Passenger);
            return ResponseResult.SUCCESS;
            //要添加的乘车人为被逻辑删除状态，所以修改其状态
        } else if (p == 1) {
            if ("n".equals(p1.getIsExit())) {
                p1.setName(g5Passenger.getName());
                p1.setGender(g5Passenger.getGender());
                p1.setIdCard(g5Passenger.getIdCard());
                p1.setTelephone(g5Passenger.getTelephone());
                p1.setEmail(g5Passenger.getEmail());
                p1.setIsExit("y");
                g5PassengerService.update(p1);
                return ResponseResult.SUCCESS;
            }
        }
        return new ResponseResult(Code.FAIL, "该乘车人已存在！");
    }

    /**
     * 删除乘车人
     *
     * @param g5Passenger 乘车人信息
     * @return 返回统一响应
     */
    @ApiOperation(value = "移除乘车人", notes = "移除乘车人，参数为乘车人信息（逻辑删除）,只是修改状态")
    @PostMapping("/del")
    public ResponseResult<Void> del(@RequestBody G5Passenger g5Passenger) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", g5Passenger.getId());
        System.out.println(g5Passenger.getId());
        long p = g5PassengerService.count(queryWrapper);
        G5Passenger p2 = g5PassengerService.getOne(queryWrapper);
        if (p == 1 && "y".equals(p2.getIsExit())) {
            g5Passenger.setIsExit("n");
            g5PassengerService.update(g5Passenger);
            return ResponseResult.SUCCESS;
        }
        return new ResponseResult(Code.FAIL, "该乘车人不存在！");
    }

    /**
     * 修改乘车人
     *
     * @param g5Passenger 乘车人信息
     * @return 返回统一响应
     */
    @ApiOperation(value = "移除乘车人", notes = "修改乘车人，修改部分信息")
    @PostMapping("/update")
    public ResponseResult<Void> update(@RequestBody G5Passenger g5Passenger) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", g5Passenger.getId());
        G5Passenger p2 = g5PassengerService.getOne(queryWrapper);
        g5Passenger.setId(p2.getId());
        g5Passenger.setTelephone(g5Passenger.getTelephone());
        g5Passenger.setEmail(g5Passenger.getEmail());
        g5PassengerService.update(g5Passenger);
        return ResponseResult.SUCCESS;
    }
}
